<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use GatewayClient\Gateway;
use app\common\service\SystemMenu as SystemMenuService;
use app\common\service\OrderMaterial;
use app\common\service\OrderUser as OrderUserService;
use app\common\service\OrderMaterial as OrderMaterialService;
use mes\Mes;
use think\Db;

/**
 * 测试
 * @author King
 *
 */
class Test extends Admin
{

    public function initialize() {
    	parent::initialize();

    }


    public function test1(){
        $orderId=117210;
        $orderMaterialService = new OrderMaterialService();

        $doneInfo = $orderMaterialService->get_order_material_list([], [367408]);

        $order_id_array=[];$mids=[367408];

        $where = [
            ['om.material_id', '>', 0],
            ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
        ];
        if ($order_id_array != []) {
            $where[] = ['om.order_id', 'in', $order_id_array];
        }
        if ($mids != []) {
            $where[] = ['om.mid', 'in', $mids];
        }
        $list_order_material = db('order_material om')
            ->field("om.mid,om.order_id,om.client_ordernum,om.material_id,om.stock_m_type,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.tiaoshu_status,om.caigou_status,om.tiaoshu
                ,om.arrive_time,om.caigou_over_time,om.caichuang_can_do
                ,m.name,m.type,m.color
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_checkcloth=1 and mi.is_return=0, mi.id,null)) as cloth_0
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_shrink=1 and mi.is_return=0, mi.id,null)) as cloth_1
                ")
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('stock_log sl', "m.type='accessories' and om.material_id=sl.material_id and om.order_id=sl.order_id", 'left')
            ->join('material_stock ms', "om.material_id=ms.material_id and ms.cutting_time=0", 'left')
            ->join('material_stock_use msu', "om.order_id=msu.order_id and om.material_id=msu.material_id", 'left')
            ->join('order_material_item mi', "om.order_id=mi.order_id and om.material_id=mi.material_id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->where($where)
            ->order('om.caichuang_standard desc')
            ->group('om.mid')
            ->select();
        echo lastsql();
        print_r($doneInfo);
        //updateCaichuangStatusV2($orderId, $orderMaterialId = 0

        /*if ($omInfo['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2
            && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $omInfo['tiaoshu_status'] != 10 && $omInfo['caigou_status'] == 1) {
            db('order_material')->where('mid', $omInfo['mid'])->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
            $obj != null && $obj->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[{$omInfo['name']}（mid {$omInfo['mid']}）]可裁剪");
        }*/
    }

    //临时功能 增加订单物料
    public function addOrderMaterial(){
        $orderId=$this->request->param('orderid', 0);
        $clientOrdernum=$this->request->param('clientOrdernum', 0);
        $materialId=943;
        $materialInfo = db('material')->find($materialId);
        $orderMaterial = [
            'order_id' => $orderId,
            'client_ordernum' => $clientOrdernum,
            'material_id' => $materialId,
            'caigou_unitprice' => $materialInfo['customer_price'], // 采购单价 目前直接使用  客户单价
            'customer_price' => $materialInfo['customer_price'], // 客户单价
            'customer_dosage' => 0.12, // 用量 目前直接使用 客户用量
            'fabric_width' => $materialInfo['fabric_width'],
            'fabric_width_once' => $materialInfo['fabric_width'],
            'weight' => $materialInfo['weight'],
            'weight_once' => $materialInfo['weight'],
            'material_dosage' => 0.12, // 米莫用量（首单取客户用量，返单优先取精准用量，没有精准用量再取最近5次裁床用量均值）
            'loss' => 0,
            'need_checkcloth' => 0,
            'need_shrink' => 1,
            'caigou_show' => 1,	// 是否在采购进度显示
            'create_time' => time(),
            'update_time' => time(),
        ];
        db('order_material')->insertGetId($orderMaterial);
    }

    public function importUsers(){
        $params = $paramsSz = $paramsOm = $paramsMl = [];
        $params['file_path']=$paramsOm['file_path']=$paramsSz['file_path']=$paramsMl['file_path'] = $_FILES['file']['tmp_name'];
        // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
        $params['start']=$paramsOm['start']=$paramsSz['start'] = $paramsMl['start'] = 2;
        // 模型（表名或模型二选一）
        $params['model']=$paramsOm['model'] = $paramsSz['model']= $paramsMl['model']  = 'cms/content';

        $resultAll = plugins_run('excel/excel/import', $params);
        if ($resultAll === false) {
            return $this->error('excel读取失败');
        }

        //检测订单号是否存在，规格、数量、单价、金额 是否数字
        $lossSku=$lossSize=$alreadyOrder=$existDatas=$alreadyJpNumbers=[];
        $insertuserKey=1;
        $result_head=array_shift($resultAll);
        foreach ($resultAll as $index => $pInfo) {
            if (trim($pInfo['A']) == '' && trim($pInfo['B'])) {
                return $this->error('excel导入数据名字不能为空，行数' . $index);
                break;
            }

            //  a序号	b工号	c姓名	d性别	e岗位
            $user = [
                'name' => $pInfo['C'], 'factory_id' => '3', 'depart_id' => '17', 'group_id' => '19', 'status' => '1',
                'number' => '1', 'jp_number' => $pInfo['B'], 'worktype' => 'cw,other', 'create_time' => time(), 'update_time' => time()
            ];
            if(empty($user['name']) && empty($user['jp_number'])) continue;
            if($user['name']=='姓名') continue;
            if (!in_array($pInfo['B'], $alreadyJpNumbers)) {
                $insertUsers[$insertuserKey] = $user;
                $insertuserKey += 1;
            }
            $alreadyJpNumbers[]=$pInfo['B'];
        }
        //============= 增加会员帐号
        $paramsSz['data'] = $insertUsers;
        $paramsSz['table'] = 'user';
        $colnums=array_keys($insertUsers[1]);$insertColnums=[];
        foreach ($colnums as $index=>$colnum){
            $insertColnums[$colnum]=$colnum;
        }
        // 列与字段的索引关系（需要自动入库的时候，此参数必须）
        $paramsSz['fields'] = $insertColnums;
        $resultMl = plugins_run('excel/excel/import', $paramsSz);
    }

    public function stocknumber(){
        $actionlist=db('cost_check cc')->join('order o', 'cc.order_id=o.id', 'left')
                ->field("cc.id as ccid,o.id as oid,cc.order_id,cc.client_ordernum")
                ->order("cc.id desc")->select();
        foreach ($actionlist as $key=>$val){
            if(empty($val['oid'])){
                //print_r($val['client_ordernum']);echo " &nbsp;&nbsp;";
                //db('cost_check')->where("id=".$val['ccid'])->delete();
                //db('stock_action')->where("id=".$val['id'])->update(['caigou_number'=>$val['caigou_number']]);
            }
        }
    }

    public function download() {
    	$pic0 = "http://file.ltwebstatic.com/spiderfile/aifd/2020/8/15976467751813068506.jpg";
    	$dowloadError = "";
    	$pic = downloadPic($pic0, $dowloadError);
    	if ($pic == '') {
    		$msg = "error:" . $dowloadError;
    	} else {
    		$msg = "local pic:{$pic} 图片下载成功";
    	}
    	echo $msg;
    }

    /**
     * 测试消息推送
     *
     * @author King
     * @date 2020年8月25日
     *
     */
	public function msg() {
		$uid = $this->request->param('uid/d', 0);
		$msg = $this->request->param('msg/s', '测试一下');

		Gateway::$registerAddress = env('register_address');

		try {
			$systemMenuService = new SystemMenuService();
			//$data = json_encode(['type' => 'message', 'msg' => $msg, 'data' => $systemMenuService->getSystemMsgUrlInfo('mp/order/materialLog', 'alert=0')]);
			$data = json_encode(['type' => 'message', 'msg' => $msg, 'data' => ['url'=>'']]);

			if ($uid) {
				if(Gateway::isUidOnline($uid)) Gateway::sendToUid($uid, $data);
				else {
					echo "用户不在线";exit;
				}
			} else {
				Gateway::sendToAll($data);
			}
			echo "ok";
		} catch (\Exception $e) {
			echo $e->getMessage();
		}
	}

	public function fix() {
		$OrderMaterial = new OrderMaterial();
		$list = db('order')->where("caigou_status=1 and caigou_over_time=0 and status < 99")->field('id,caichuang_over_time')->select();


		echo 'ok';
	}

	public function bundle() {
		$orderUserService = new OrderUserService();
		$orderUserService->makeBundle('52881', true);
		echo 'ok';
	}

	public function status() {
		$orderMaterialService = new OrderMaterialService();
		$omList = $orderMaterialService->getListByOrderIdForCutting(66951, ['fabric', 'lining']);
		print_r($omList);
		if (array_sum(array_column($omList, 'caichuang_pull_status')) == count($omList)) {

			// 更新订单表，标识订单已裁剪完成
			$orderData = [
				'caichuang_status' => 1,
				'caichuang_over_time' => time(),
			];
			print_r($orderData);
		} else {
			echo "NONONO";
		}
	}

	public function mesapi() {
        set_time_limit(0);
        ini_set('memory_limit', '512M');
        error_reporting(E_ALL & ~E_NOTICE);

        $mesLib = new Mes();
		$mes = 2;
		$config = [
			'private_key' => env("mes{$mes}.private_key"),
			'app_id' => env("mes{$mes}.app_id"),
			'app_secure' => env("mes{$mes}.app_secure"),
			'host' => env("mes{$mes}.host"),
			];
		$mesLib->setConfig($config);
       // $redis = getRedis();
		$result = [];
        $sql='SELECT  is_auto_import,client_ordernum,`status`,client_status,FROM_UNIXTIME(create_time,"%Y-%m-%d") as add_time  from  wx_order where `status` in(0,1) and client_status !=99 
         and is_auto_import=1  ';
        $sql2 = $sql.' GROUP BY  add_time  ORDER BY   add_time asc';
         $list=Db::query($sql2);
        foreach ($list as $key=>$value){

            $result = $mesLib->queryProduceOrderInfoV2($value['add_time'].' 00:00:00',$value['add_time'].' 23:59:59' );
            $data = json_decode($result, true);

            addLog(count($data['info']),  'CountQueryProduceOrderInfoV2');

            if(!empty($data['info'])){

                foreach ($data['info'] as  $key2=>$value2){
                        $clientOrderStatus=$value2['status'];
                        // 记录客户订单状态
                        $clientStatus = array_search($clientOrderStatus, config('mimo.client_status'));
                        $orderData['client_status'] = $clientStatus===false?1000:$clientStatus;
                        $orderData['client_status_txt'] = $clientOrderStatus;
                        $orderData['update_time'] = time();
                        if ($clientStatus === false) {
                            $msg = "客户订单号 {$value2['produceOrderId']} 客户订单状态异常：" . $clientOrderStatus;
                            addLog($msg, 'no');
                        }
                        $Ok=db('order')->where('client_ordernum', $value2['produceOrderId'])->update($orderData);
                          addLog($value2['produceOrderId'], 'InsertQueryProduceOrderInfo');
                }
            }

        }
        echo 'done';
        exit;
		//$result = $mesLib->queryProduceOrderInfo('2021-08-26 17:15:16', '2021-08-26 17:15:16');

		//$result = $mesLib->getProduceOrderInfo('7432562');
		//$result = $mesLib->purchaseDetailInfoList('7679230');
		//$result = $mesLib->getOrderInfo([7622237]);
		//$result = $mesLib->getDeliverOrderList([7445487]);
		//$result = $mesLib->getBigGoodsBom(7445487);
		//echo $result;exit;
		$result = json_decode($result, true);
		print_r($result);
	}

}